<template>
  <div class="admin-dashboard">
    <!-- 复用管理员侧边栏 -->
    <div class="admin-sidebar">
      <div class="admin-sidebar-header">
        <h2>管理控制台</h2>
      </div>
      <ul class="admin-menu">
        <li>
          <router-link to="/admin/dashboard" class="menu-item" active-class="active">
            <span class="menu-icon">📊</span>
            <span class="menu-text">仪表盘</span>
          </router-link>
        </li>
        <li>
          <router-link to="/admin/users" class="menu-item" active-class="active">
            <span class="menu-icon">👥</span>
            <span class="menu-text">用户管理</span>
          </router-link>
        </li>
        <li>
          <router-link to="/admin/questions" class="menu-item" active-class="active">
            <span class="menu-icon">❓</span>
            <span class="menu-text">问答管理</span>
          </router-link>
        </li>
        <li>
          <router-link to="/admin/stories" class="menu-item" active-class="active">
            <span class="menu-icon">📖</span>
            <span class="menu-text">故事管理</span>
          </router-link>
        </li>
      </ul>
      <div class="admin-sidebar-footer">
        <button @click="handleLogout" class="logout-btn">退出登录</button>
      </div>
    </div>

    <!-- 管理员主内容区 -->
    <div class="admin-main-content">
      <div class="admin-header">
        <h1>问答管理</h1>
        <div class="admin-user-info">
          <span>欢迎，{{ currentUser?.username }}</span>
        </div>
      </div>
      
      <!-- 搜索和筛选 -->
      <div class="filter-section">
        <input 
          type="text" 
          v-model="searchQuery" 
          placeholder="搜索问题内容"
          class="search-input"
        />
        <select v-model="statusFilter" class="filter-select">
          <option value="all">全部状态</option>
          <option value="pending">待回答</option>
          <option value="answered">已回答</option>
          <option value="highlighted">精选</option>
        </select>
      </div>

      <!-- 问答列表 -->
      <div class="questions-table-container">
        <table class="questions-table">
          <thead>
            <tr>
              <th>ID</th>
              <th>提问用户</th>
              <th>问题标题</th>
              <th>问题内容</th>
              <th>提问时间</th>
              <th>状态</th>
              <th>操作</th>
            </tr>
          </thead>
          <tbody>
            <tr v-for="question in filteredQuestions" :key="question.id">
              <td>{{ question.id }}</td>
              <td>{{ question.username }}</td>
              <td>{{ question.title }}</td>
              <td class="question-content">{{ truncateText(question.content, 50) }}</td>
              <td>{{ formatDate(question.createdAt) }}</td>
              <td>
                <span :class="['status-badge', question.status]">
                  {{ getStatusText(question.status) }}
                </span>
              </td>
              <td>
                <button @click="viewQuestion(question)" class="action-btn view-btn">查看</button>
                <button @click="highlightQuestion(question)" class="action-btn highlight-btn">
                  {{ question.status === 'highlighted' ? '取消精选' : '设为精选' }}
                </button>
                <button @click="deleteQuestion(question.id)" class="action-btn delete-btn">删除</button>
              </td>
            </tr>
          </tbody>
        </table>
        <p v-if="filteredQuestions.length === 0" class="no-data">没有找到符合条件的问题</p>
      </div>

      <!-- 查看问题对话框 -->
      <div v-if="showQuestionModal" class="modal-overlay" @click.self="closeModal">
        <div class="modal-content question-modal">
          <h3>{{ currentQuestion?.title }}</h3>
          <div class="question-detail">
            <div class="question-info">
              <span class="info-item">提问者：{{ currentQuestion?.username }}</span>
              <span class="info-item">提问时间：{{ formatDate(currentQuestion?.createdAt) }}</span>
            </div>
            <div class="question-body">
              <p>{{ currentQuestion?.content }}</p>
            </div>
            <div class="answers-section">
              <h4>回答 ({{ currentQuestion?.answers?.length || 0 }})</h4>
              <div v-if="currentQuestion?.answers && currentQuestion.answers.length > 0" class="answers-list">
                <div v-for="(answer, index) in currentQuestion.answers" :key="index" class="answer-item">
                  <div class="answer-header">
                    <span class="answer-author">{{ answer.author }}</span>
                    <span class="answer-time">{{ formatDate(answer.createdAt) }}</span>
                  </div>
                  <div class="answer-content">
                    <p>{{ answer.content }}</p>
                  </div>
                </div>
              </div>
              <p v-else class="no-answers">暂无回答</p>
            </div>
          </div>
          <div class="modal-actions">
            <button @click="closeModal" class="cancel-btn">关闭</button>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import { userStore } from '../../stores/user'

export default {
  name: 'QuestionsView',
  data() {
    return {
      questions: [],
      searchQuery: '',
      statusFilter: 'all',
      showQuestionModal: false,
      currentQuestion: null,
      currentUser: null
    }
  },
  computed: {
    userState() {
      const state = userStore.getState()
      return state
    },
    filteredQuestions() {
      let result = [...this.questions]
      
      // 搜索过滤
      if (this.searchQuery) {
        const query = this.searchQuery.toLowerCase()
        result = result.filter(question => 
          question.title.toLowerCase().includes(query) || 
          question.content.toLowerCase().includes(query)
        )
      }
      
      // 状态过滤
      if (this.statusFilter !== 'all') {
        result = result.filter(question => question.status === this.statusFilter)
      }
      
      return result
    }
  },
  mounted() {
    // 检查用户是否已登录且是管理员
    this.checkAdminAccess()
    this.loadQuestions()
  },
  methods: {
    checkAdminAccess() {
      if (!this.userState.isAuthenticated || !this.userState.currentUser.isAdmin) {
        this.$router.push('/admin/login')
      } else {
        this.currentUser = this.userState.currentUser
      }
    },
    loadQuestions() {
      // 模拟从API获取问答数据
      this.questions = [
        {
          id: 1,
          username: 'testuser',
          title: '如何处理分手带来的痛苦？',
          content: '我刚刚经历了一场痛苦的分手，感觉整个人都很糟糕，不知道该如何走出这种情绪...',
          createdAt: new Date('2024-01-15T10:30:00'),
          status: 'answered',
          answers: [
            {
              author: '情感专家',
              content: '分手确实是很痛苦的经历。建议你给自己足够的时间悲伤，同时尝试做一些自己喜欢的事情转移注意力...',
              createdAt: new Date('2024-01-15T14:20:00')
            }
          ]
        },
        {
          id: 2,
          username: 'memberuser',
          title: '如何维持长久的恋爱关系？',
          content: '我和男朋友在一起两年了，最近感觉关系有些平淡，不知道如何保持新鲜感...',
          createdAt: new Date('2024-01-14T09:15:00'),
          status: 'highlighted',
          answers: [
            {
              author: '恋爱达人',
              content: '长久的关系需要双方共同努力。建议你们定期安排约会之夜，保持良好的沟通，同时也要给彼此一些个人空间...',
              createdAt: new Date('2024-01-14T11:45:00')
            }
          ]
        },
        {
          id: 3,
          username: 'user4',
          title: '如何向暗恋的人表白？',
          content: '我喜欢上了公司的同事，但不知道如何开口表白，害怕被拒绝连朋友都做不成...',
          createdAt: new Date('2024-01-13T16:40:00'),
          status: 'pending',
          answers: []
        }
      ]
    },
    truncateText(text, maxLength) {
      if (!text) return ''
      return text.length > maxLength ? text.substring(0, maxLength) + '...' : text
    },
    formatDate(date) {
      if (!date) return ''
      const d = new Date(date)
      return d.toLocaleString('zh-CN', {
        year: 'numeric',
        month: '2-digit',
        day: '2-digit',
        hour: '2-digit',
        minute: '2-digit'
      })
    },
    getStatusText(status) {
      const statusMap = {
        pending: '待回答',
        answered: '已回答',
        highlighted: '精选'
      }
      return statusMap[status] || status
    },
    viewQuestion(question) {
      this.currentQuestion = question
      this.showQuestionModal = true
    },
    highlightQuestion(question) {
      if (question.status === 'highlighted') {
        question.status = question.answers && question.answers.length > 0 ? 'answered' : 'pending'
      } else {
        question.status = 'highlighted'
      }
    },
    deleteQuestion(questionId) {
      if (confirm('确定要删除这个问题吗？相关的回答也会被删除。')) {
        this.questions = this.questions.filter(q => q.id !== questionId)
      }
    },
    closeModal() {
      this.showQuestionModal = false
      this.currentQuestion = null
    },
    handleLogout() {
      userStore.logout()
      this.$router.push('/admin/login')
    }
  }
}
</script>

<style scoped>
/* 复用管理员侧边栏样式 */
.admin-sidebar {
  width: 250px;
  background-color: #2c3e50;
  color: white;
  padding: 20px 0;
}

.admin-sidebar-header {
  padding: 0 20px 30px;
  border-bottom: 1px solid #34495e;
}

.admin-sidebar-header h2 {
  margin: 0;
  font-size: 18px;
}

.admin-menu {
  list-style: none;
  padding: 0;
  margin: 20px 0;
}

.menu-item {
  display: flex;
  align-items: center;
  padding: 15px 20px;
  color: #bdc3c7;
  text-decoration: none;
  transition: all 0.3s;
}

.menu-item:hover {
  background-color: #34495e;
  color: white;
}

.menu-item.active {
  background-color: #4CAF50;
  color: white;
}

.menu-icon {
  margin-right: 15px;
  font-size: 18px;
}

.admin-sidebar-footer {
  padding: 20px;
  border-top: 1px solid #34495e;
  margin-top: auto;
}

.logout-btn {
  width: 100%;
  padding: 10px;
  background-color: #e74c3c;
  color: white;
  border: none;
  border-radius: 4px;
  cursor: pointer;
  transition: background-color 0.3s;
}

.logout-btn:hover {
  background-color: #c0392b;
}

/* 管理员主内容区 */
.admin-main-content {
  flex: 1;
  padding: 20px 30px;
  overflow-y: auto;
  max-width: 100%;
  overflow-x: auto;
}

.admin-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 30px;
}

.admin-header h1 {
  margin: 0;
  color: #2c3e50;
}

.admin-user-info {
  color: #7f8c8d;
}

/* 筛选部分 */
.filter-section {
  display: flex;
  gap: 15px;
  margin-bottom: 20px;
}

.search-input {
  flex: 1;
  padding: 10px;
  border: 1px solid #ddd;
  border-radius: 4px;
}

.filter-select {
  padding: 10px;
  border: 1px solid #ddd;
  border-radius: 4px;
  background-color: white;
}

/* 问答表格 */
.questions-table-container {
  background-color: white;
  border-radius: 8px;
  padding: 20px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
  overflow-x: auto;
}

.questions-table {
  width: 100%;
  border-collapse: collapse;
}

.questions-table th,
.questions-table td {
  padding: 12px;
  text-align: left;
  border-bottom: 1px solid #ecf0f1;
}

.questions-table th {
  background-color: #f8f9fa;
  font-weight: 600;
  color: #2c3e50;
}

.question-content {
  max-width: 200px;
  word-break: break-word;
}

/* 状态标签 */
.status-badge {
  padding: 4px 8px;
  border-radius: 12px;
  font-size: 12px;
  font-weight: 500;
}

.status-badge.pending {
  background-color: #fff3cd;
  color: #856404;
}

.status-badge.answered {
  background-color: #d1ecf1;
  color: #0c5460;
}

.status-badge.highlighted {
  background-color: #f8d7da;
  color: #721c24;
}

/* 操作按钮 */
.action-btn {
  padding: 6px 12px;
  border: none;
  border-radius: 4px;
  cursor: pointer;
  font-size: 14px;
  margin-right: 5px;
  transition: background-color 0.3s;
}

.view-btn {
  background-color: #2196f3;
  color: white;
}

.view-btn:hover {
  background-color: #1976d2;
}

.highlight-btn {
  background-color: #ff9800;
  color: white;
}

.highlight-btn:hover {
  background-color: #f57c00;
}

.delete-btn {
  background-color: #f44336;
  color: white;
}

.delete-btn:hover {
  background-color: #d32f2f;
}

.no-data {
  text-align: center;
  color: #7f8c8d;
  padding: 20px;
}

/* 问题详情模态框 */
.question-modal {
  width: 90%;
  max-width: 800px;
  max-height: 80vh;
  overflow-y: auto;
}

.question-detail {
  margin-bottom: 20px;
}

.question-info {
  display: flex;
  gap: 20px;
  margin-bottom: 15px;
  color: #666;
  font-size: 14px;
}

.question-body {
  margin-bottom: 30px;
  line-height: 1.6;
}

.answers-section h4 {
  margin: 0 0 15px;
  padding-bottom: 10px;
  border-bottom: 1px solid #eee;
}

.answer-item {
  padding: 15px;
  border-bottom: 1px solid #f0f0f0;
}

.answer-item:last-child {
  border-bottom: none;
}

.answer-header {
  display: flex;
  justify-content: space-between;
  margin-bottom: 10px;
  font-size: 14px;
}

.answer-author {
  font-weight: 600;
  color: #2c3e50;
}

.answer-time {
  color: #999;
}

.answer-content {
  line-height: 1.6;
}

.no-answers {
  text-align: center;
  color: #999;
  padding: 20px;
  font-style: italic;
}

.modal-actions {
  display: flex;
  justify-content: flex-end;
  margin-top: 20px;
}

.cancel-btn {
  padding: 10px 20px;
  background-color: #f1f1f1;
  color: #333;
  border: none;
  border-radius: 4px;
  cursor: pointer;
}

.cancel-btn:hover {
  background-color: #e0e0e0;
}
</style>